package com.back.service.impl;

import com.back.dto.InvitationTemplateDTO;
import com.back.entity.InterviewInvitationTemplate;
import com.back.mapper.InterviewInvitationTemplateMapper;
import com.back.service.IInterviewInvitationTemplateService;
import com.back.vo.InvitationTemplateVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  面试邀请模板服务实现类
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@Service
public class InterviewInvitationTemplateServiceImpl extends ServiceImpl<InterviewInvitationTemplateMapper, InterviewInvitationTemplate> implements IInterviewInvitationTemplateService {

    @Override
    public IPage<InvitationTemplateVO> getTemplateList(Page<InterviewInvitationTemplate> page, Long companyId) {
        // 构建查询条件
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getDeleted, false)
                    .orderByDesc(InterviewInvitationTemplate::getIsDefault)
                    .orderByDesc(InterviewInvitationTemplate::getCreateTime);
        
        // 执行分页查询
        Page<InterviewInvitationTemplate> templatePage = page(page, queryWrapper);
        
        // 转换为VO
        Page<InvitationTemplateVO> resultPage = new Page<>();
        BeanUtils.copyProperties(templatePage, resultPage, "records");
        
        // 转换记录
        List<InvitationTemplateVO> templateVOList = templatePage.getRecords().stream().map(template -> {
            InvitationTemplateVO templateVO = new InvitationTemplateVO();
            BeanUtils.copyProperties(template, templateVO);
            return templateVO;
        }).collect(Collectors.toList());
        
        resultPage.setRecords(templateVOList);
        
        return resultPage;
    }

    @Override
    public InvitationTemplateVO createTemplate(InvitationTemplateDTO templateDTO, Long creatorId) {
        // 创建模板实体
        InterviewInvitationTemplate template = new InterviewInvitationTemplate();
        BeanUtils.copyProperties(templateDTO, template);
        
        // 设置其他属性
        template.setCreatorId(creatorId);
        long currentTime = System.currentTimeMillis();
        template.setCreateTime(currentTime);
        template.setUpdateTime(currentTime);
        template.setDeleted(false);
        
        // 如果设置为默认模板，需要将其他模板设置为非默认
        if (templateDTO.getIsDefault() != null && templateDTO.getIsDefault()) {
            resetDefaultTemplates(templateDTO.getCompanyId());
        } else {
            // 如果没有指定是否默认，则设置为非默认
            template.setIsDefault(false);
        }
        
        // 保存到数据库
        save(template);
        
        // 转换为VO返回
        InvitationTemplateVO templateVO = new InvitationTemplateVO();
        BeanUtils.copyProperties(template, templateVO);
        
        return templateVO;
    }

    @Override
    public InvitationTemplateVO updateTemplate(Long id, Long companyId, InvitationTemplateDTO templateDTO) {
        // 查询模板
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getId, id)
                    .eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getDeleted, false);
        
        InterviewInvitationTemplate template = getOne(queryWrapper);
        if (template == null) {
            return null;
        }
        
        // 更新属性
        BeanUtils.copyProperties(templateDTO, template, "companyId", "creatorId");
        template.setUpdateTime(System.currentTimeMillis());
        
        // 如果设置为默认模板，需要将其他模板设置为非默认
        if (templateDTO.getIsDefault() != null && templateDTO.getIsDefault() && !template.getIsDefault()) {
            resetDefaultTemplates(companyId);
        }
        
        // 保存到数据库
        updateById(template);
        
        // 转换为VO返回
        InvitationTemplateVO templateVO = new InvitationTemplateVO();
        BeanUtils.copyProperties(template, templateVO);
        
        return templateVO;
    }

    @Override
    public boolean deleteTemplate(Long id, Long companyId) {
        // 查询模板
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getId, id)
                    .eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getDeleted, false);
        
        InterviewInvitationTemplate template = getOne(queryWrapper);
        if (template == null) {
            return false;
        }
        
        // 逻辑删除
        template.setDeleted(true);
        template.setUpdateTime(System.currentTimeMillis());
        
        return updateById(template);
    }

    @Override
    public InvitationTemplateVO getTemplateDetail(Long id, Long companyId) {
        // 查询模板
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getId, id)
                    .eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getDeleted, false);
        
        InterviewInvitationTemplate template = getOne(queryWrapper);
        if (template == null) {
            return null;
        }
        
        // 转换为VO
        InvitationTemplateVO templateVO = new InvitationTemplateVO();
        BeanUtils.copyProperties(template, templateVO);
        
        return templateVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultTemplate(Long id, Long companyId) {
        // 查询模板
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getId, id)
                    .eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getDeleted, false);
        
        InterviewInvitationTemplate template = getOne(queryWrapper);
        if (template == null) {
            return false;
        }
        
        // 如果已经是默认模板，不需要操作
        if (template.getIsDefault()) {
            return true;
        }
        
        // 重置其他默认模板
        resetDefaultTemplates(companyId);
        
        // 设置当前模板为默认
        template.setIsDefault(true);
        template.setUpdateTime(System.currentTimeMillis());
        
        return updateById(template);
    }

    @Override
    public InvitationTemplateVO getDefaultTemplate(Long companyId) {
        // 查询默认模板
        LambdaQueryWrapper<InterviewInvitationTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getIsDefault, true)
                    .eq(InterviewInvitationTemplate::getDeleted, false);
        
        InterviewInvitationTemplate template = getOne(queryWrapper);
        if (template == null) {
            // 如果没有默认模板，返回最新创建的一个
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(InterviewInvitationTemplate::getCompanyId, companyId)
                        .eq(InterviewInvitationTemplate::getDeleted, false)
                        .orderByDesc(InterviewInvitationTemplate::getCreateTime)
                        .last("LIMIT 1");
            
            template = getOne(queryWrapper);
            if (template == null) {
                return null;
            }
        }
        
        // 转换为VO
        InvitationTemplateVO templateVO = new InvitationTemplateVO();
        BeanUtils.copyProperties(template, templateVO);
        
        return templateVO;
    }
    
    /**
     * 重置公司的所有默认模板
     * @param companyId 公司ID
     */
    private void resetDefaultTemplates(Long companyId) {
        LambdaUpdateWrapper<InterviewInvitationTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InterviewInvitationTemplate::getCompanyId, companyId)
                    .eq(InterviewInvitationTemplate::getIsDefault, true)
                    .eq(InterviewInvitationTemplate::getDeleted, false)
                    .set(InterviewInvitationTemplate::getIsDefault, false)
                    .set(InterviewInvitationTemplate::getUpdateTime, System.currentTimeMillis());
        
        update(updateWrapper);
    }
}
